package mushystuff.dtb.web.endpoint;

import java.util.ArrayList;
import java.util.Collection;

import javax.xml.rpc.ServiceException;

import mushystuff.dtb.core.model.Product;
import mushystuff.dtb.core.service.ProductService;
import mushystuff.dtb.web.vo.ProductVO;

import org.springframework.remoting.jaxrpc.ServletEndpointSupport;

public class ProductServiceEndpoint extends ServletEndpointSupport {

    private static ProductService productService;

    @Override
    protected void onInit() throws ServiceException {
        if (productService == null) {
            productService = (ProductService) getWebApplicationContext()
                    .getBean("productService");
        }
    }
    
    public void createProduct(String name) {
        Product product = new Product();
        product.setName(name);
        productService.createUpdateProduct(product);
    }
    
    public void modifyProduct(long id, String name, boolean active) {
        Product product = productService.getProduct(id);
        product.setName(name);
        product.setActive(active);
        productService.createUpdateProduct(product);
    }
    
    public ProductVO[] getAllProducts() {
        return ProductVO.convert(productService.getAllProducts());
    }
    
    // Todo: Should be able to do this in actionscript.
    public ProductVO[] getAllActiveProductsWithEmpty() {
        Collection<Product> products = new ArrayList<Product>();
        Product blankProduct = new Product();
        blankProduct.setId(-1L);
        blankProduct.setName("Select Product");
        products.add(blankProduct);
        products.addAll(productService.getAllActiveProducts());
        return ProductVO.convert(products);
    }
}
